#!/bin/bash

# SSL证书获取和配置脚本
# 使用Let's Encrypt为pecco宠物用品网站配置HTTPS

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# 日志函数
log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检查是否为root用户
check_root() {
    if [ "$EUID" -ne 0 ]; then
        log_error "请使用root权限运行此脚本"
        exit 1
    fi
}

# 检查域名配置
check_domain() {
    if [ -z "$DOMAIN" ]; then
        log_error "请设置DOMAIN环境变量，例如: export DOMAIN=pecco.pet"
        exit 1
    fi
    
    if [ -z "$EMAIL" ]; then
        log_error "请设置EMAIL环境变量，例如: export EMAIL=admin@pecco.pet"
        exit 1
    fi
    
    log_info "域名: $DOMAIN"
    log_info "邮箱: $EMAIL"
}

# 安装certbot
install_certbot() {
    log_info "检查并安装certbot..."
    
    if command -v certbot &> /dev/null; then
        log_info "certbot已安装"
        return
    fi
    
    # 检测操作系统
    if [ -f /etc/debian_version ]; then
        # Debian/Ubuntu
        apt-get update
        apt-get install -y certbot
    elif [ -f /etc/redhat-release ]; then
        # CentOS/RHEL
        yum install -y epel-release
        yum install -y certbot
    else
        log_error "不支持的操作系统，请手动安装certbot"
        exit 1
    fi
    
    log_info "certbot安装完成"
}

# 创建证书目录
create_cert_dirs() {
    log_info "创建证书目录..."
    mkdir -p /etc/letsencrypt
    mkdir -p /var/lib/letsencrypt
    mkdir -p /var/log/letsencrypt
    mkdir -p ./ssl-certs
}

# 停止nginx容器以释放80端口
stop_nginx() {
    log_info "临时停止nginx容器..."
    docker-compose -f docker-compose.prod.yml stop nginx || true
}

# 获取SSL证书
obtain_certificate() {
    log_info "获取SSL证书..."
    
    # 使用standalone模式获取证书
    certbot certonly \
        --standalone \
        --non-interactive \
        --agree-tos \
        --email "$EMAIL" \
        -d "$DOMAIN" \
        -d "www.$DOMAIN" \
        --cert-path /etc/letsencrypt/live/$DOMAIN/cert.pem \
        --key-path /etc/letsencrypt/live/$DOMAIN/privkey.pem \
        --fullchain-path /etc/letsencrypt/live/$DOMAIN/fullchain.pem \
        --chain-path /etc/letsencrypt/live/$DOMAIN/chain.pem
    
    if [ $? -eq 0 ]; then
        log_info "SSL证书获取成功"
    else
        log_error "SSL证书获取失败"
        exit 1
    fi
}

# 复制证书到项目目录
copy_certificates() {
    log_info "复制证书到项目目录..."
    
    # 创建ssl-certs目录
    mkdir -p ./ssl-certs
    
    # 复制证书文件
    cp /etc/letsencrypt/live/$DOMAIN/fullchain.pem ./ssl-certs/
    cp /etc/letsencrypt/live/$DOMAIN/privkey.pem ./ssl-certs/
    
    # 设置权限
    chmod 644 ./ssl-certs/fullchain.pem
    chmod 600 ./ssl-certs/privkey.pem
    
    log_info "证书复制完成"
}

# 重启nginx容器
restart_nginx() {
    log_info "重启nginx容器..."
    docker-compose -f docker-compose.prod.yml up -d nginx
    
    # 等待nginx启动
    sleep 10
    
    # 检查nginx状态
    if docker-compose -f docker-compose.prod.yml ps nginx | grep -q "Up"; then
        log_info "nginx重启成功"
    else
        log_error "nginx重启失败"
        exit 1
    fi
}

# 测试HTTPS连接
test_https() {
    log_info "测试HTTPS连接..."
    
    # 等待一段时间让服务完全启动
    sleep 15
    
    # 测试HTTP重定向
    if curl -s -I "http://$DOMAIN" | grep -q "301\|302"; then
        log_info "HTTP到HTTPS重定向正常"
    else
        log_warn "HTTP重定向可能有问题"
    fi
    
    # 测试HTTPS连接
    if curl -s -I "https://$DOMAIN" | grep -q "200"; then
        log_info "HTTPS连接正常"
    else
        log_warn "HTTPS连接可能有问题"
    fi
}

# 主函数
main() {
    log_info "开始配置SSL证书..."
    
    check_root
    check_domain
    install_certbot
    create_cert_dirs
    stop_nginx
    obtain_certificate
    copy_certificates
    restart_nginx
    test_https
    
    log_info "SSL证书配置完成！"
    log_info "您的网站现在可以通过 https://$DOMAIN 访问"
    log_info "请记得设置定时任务来自动续期证书"
}

# 运行主函数
main "$@"
